<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择商品"
    width="90%"
    :close-on-click-modal="false"
    append-to-body
    teleported="body"
    @close="handleCancel"
  >
    <BasicTable
      ref="tableRef"
      :api="getSpuPage"
      :useSearchForm="useSearchForm"
      :columns="columns"
      :pagination="{
        pageString: 'pageNo',
        pageSizeString: 'pageSize'
      }"
      :selectionColumn="selectionColumn"
      :responseStructure="responseStructure"
      @select-all="handleSelectAll"
      @selection-change="handleSelectionChange"
    >
      <template #picUrl="{ record }">
        <el-image :src="record.row.picUrl" style="width: 100px; height: 100px" fit="cover" />
      </template>
    </BasicTable>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, computed } from 'vue'
import { BasicTable } from '@/components/BasicTable'
import { columns, useSearchForm, responseStructure } from './index.data'
import { getSpuPage } from '@/api/mall/product/spu'

const props = defineProps({
  visible: { type: Boolean, default: false },
  selectedGoods: { type: Array, default: () => [] }
})
const emit = defineEmits(['update:visible', 'confirm'])
const selectedRows = ref<any[]>([])

// 计算已选商品的ID集合
const selectedGoodsIds = computed(() => {
  const ids = new Set((props.selectedGoods as any[]).map((item) => item.productId || item.id))
  return ids
})

const dialogVisible = ref(props.visible)
watch(
  () => props.visible,
  (v) => {
    dialogVisible.value = v
    // 重置选中的行
    selectedRows.value = []
    if (v) {
      // 弹窗打开时，重新加载表格
      setTimeout(() => {
        tableRef.value?.reload()
        // 确保重置表格选择状态
        tableRef.value?.toggleSelection()
      }, 100)
    }
  }
)
watch(dialogVisible, (v) => emit('update:visible', v))

const tableRef = ref<InstanceType<typeof BasicTable>>()
const selectionColumn = ref({
  type: 'selection',
  width: 55,
  selectable: (row: any) => {
    // 如果商品已被选择，则禁用
    return !selectedGoodsIds.value.has(row.id)
  }
})

const handleCancel = () => {
  dialogVisible.value = false
}

const handleConfirm = () => {
  // 过滤掉已选的商品，只返回新选择的商品
  const newSelectedGoods = selectedRows.value.filter((row) => {
    const hasSelected = selectedGoodsIds.value.has(row.id)
    return !hasSelected
  })
  if (newSelectedGoods.length === 0) {
    console.log('handleConfirm - 警告：没有新选择的商品')
  }

  emit('confirm', newSelectedGoods)
  selectedRows.value = []
  dialogVisible.value = false
}

const handleSelectAll = (val: any) => {
  console.log(val)
}

const handleSelectionChange = (val: any) => {
  selectedRows.value = val
}
</script>
